package com.imm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imm.common.Result;
import com.imm.dto.UserDTO;
import com.imm.mapper.UserMapper;
import com.imm.pojo.User;
import com.imm.service.IUserService;
import com.imm.utils.SMSSendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private SMSSendService smsSendService;

    @Resource
    private UserMapper userMapper;

    /**
     * 手机验证码发送
     * @param user 用户对象
     * @return 响应
     */
    @Override
    public Result<String> sendMsg(User user) {
        if (StringUtils.isEmpty(user.getPhone())) {
            return Result.error("错误");
        }
        // 发送验证码
        String code = RandomStringUtils.randomNumeric(6);
        smsSendService.sendCode(user.getPhone(), code);
        return Result.success("短信发送成功");
    }

    @Override
    public Result<User> login(UserDTO userDTO, HttpSession session) {
        if (StringUtils.isEmpty(userDTO.getPhone()) || StringUtils.isEmpty(userDTO.getCode())) {
            return Result.error("错误");
        }
        // 检查用户是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, userDTO.getPhone());
        User user = getOne(wrapper);
        if (user == null) {
            User newUser = new User();
            newUser.setPhone(userDTO.getPhone());
            newUser.setStatus(1);
            // 新建用户
            userMapper.insert(newUser);
            user = newUser;
        }
        // 写进session
        session.setAttribute("user", user.getId());
        return Result.success(user);
    }
}
